package org.bb.imserver.handler;

import org.bb.im.packet.HelloPacket;
import org.bb.im.util.PacketUtil;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.stereotype.Component;
import org.tio.common.starter.annotation.TioServerMsgHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.Tio;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.core.starter.handler.TioServerAioHandler;

import java.nio.ByteBuffer;

/**
 * 消息处理handler,通过添加{@link org.tio.common.starter.annotation.TioServerMsgHandler}注解启用，否则不启用
 * 注意：handler是必须要启动的，否则会抛出{@link org.tio.common.starter.TioServerMsgHandlerNotFoundException} 异常
 *
 * @author qwer1
 */
@Component
@TioServerMsgHandler
public class HelloServerMsgHandler implements TioServerAioHandler {
    @Override
    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws AioDecodeException {
        return PacketUtil.decode(buffer, limit, position, readableLength, channelContext);
    }

    @Override
    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        return PacketUtil.encode(packet, groupContext, channelContext);
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        HelloPacket helloPacket = (HelloPacket) packet;
        byte[] body = helloPacket.getBody();
        if (body != null) {
            String str = new String(body, HelloPacket.CHARSET);
            System.out.println("收到消息:" + str);

            HelloPacket resppacket = new HelloPacket();
            resppacket.setBody(("收到了你的消息，你的消息shi:" + str).getBytes(HelloPacket.CHARSET));
            Tio.send(channelContext, resppacket);
        }
        return;
    }
}
